package com.raycloud.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

public class FileUtil {
	private static final Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 * 判断文件目录存不存在，如果不存在就创建所有子目录
	 * 
	 * @param filePath
	 */
	public static void checkOrCreateFile(String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public static String getMinSplit(String mm) {
		Integer i = Integer.valueOf(mm);
		return String.valueOf(i / 10);
	}

	public static void deleteFile(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			file.delete();
		} else {
			logger.error("delete file path " + filePath + " is not exists");
		}
	}
	
	public static void deleteFile(File file) {
		if (file.exists()) {
			file.delete();
		} else {
			logger.error("delete file path " + file.getAbsolutePath() + " is not exists");
		}
	}
	
	/**
	 * 得到文件后缀
	 * @param fileName
	 * @return
	 */
	public static String getFileSuffix(String fileName) {
		int index = fileName.lastIndexOf(".");
		return fileName.substring(index + 1);
	}
	
	/**
	 * 把oldName的文件修改成新文件
	 * 
	 * @param oldName
	 * @param newName
	 */
	public static final boolean changeFileName(String oldName, String newName) {
		File file = new File(oldName);
		if (file.exists()) {
			File newFile = new File(newName);
			return file.renameTo(newFile);
		}
		return false;
	}

	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			File newFile = new File(newPath);
			String parentPath = getFileParentPath(newPath);
			File newFileParentFile = new File(parentPath);
			if(!newFileParentFile.exists()) {
				newFileParentFile.mkdirs();
			}
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldfile); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newFile);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}else{
				logger.error("copy file is notexists == url == " + oldPath);
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();
		}
	}
	
	public static boolean copyFile1(String oldPathFile, String newPathFile) {
		int bytesum = 0;
		int byteread = 0;
		File oldfile = new File(oldPathFile);
		String parentPath = getFileParentPath(newPathFile);
		File newFileParentFile = new File(parentPath);
		if(!newFileParentFile.exists()) {
			newFileParentFile.mkdirs();
		}
		try {
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件
				String path = newPathFile.substring(0, newPathFile
						.lastIndexOf(File.separator));
				if (!new File(path).exists()) {
					return false;
				}
				FileOutputStream fs = new FileOutputStream(newPathFile);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	
	public static long copyFileByChannel(File f1,File f2) throws Exception{
        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(f1);
        FileOutputStream out=new FileOutputStream(f2);
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        ByteBuffer b=null;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();
                return new Date().getTime()-time;
            }
            if((inC.size()-inC.position())<length){
                length=(int)(inC.size()-inC.position());
            }else
                length=2097152;
            b=ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }
    }
	
	public static List<Long> getTaobaoIdsFromFile(String path) {
		File file = new File(path);
		File[] subFile = file.listFiles();
		if(subFile != null) {
			List<Long> tids = new ArrayList<Long>();
			for (File dic : subFile) {
				if(dic.isDirectory()) {
					try {
						tids.add(Long.valueOf(dic.getName()));
					} catch (Exception e) {
						logger.error("directory == " + dic.getAbsolutePath() + " " + e.getMessage());
					}
				}
			}
			return tids;
		}
		return null;
	}
	
	private static String getFileParentPath(String path) {
		int index = path.lastIndexOf(File.separator);
		String newPath = path.substring(0, index);
		return newPath;
	}
	
	public static void main(String[] args) {
		System.out.println(getFileSuffix("xxx.jpg"));
		getTaobaoIdsFromFile("/Users/flylampard/wangyi/project/java3/promotion_img_editor/WebRoot/swf/2011-09-17");
	}
}
